package com.idenger.modules.edu.web.comm;

import com.idenger.common.config.Global;
import com.idenger.common.utils.FileUtils;
import com.idenger.common.web.BaseController;
import com.idenger.modules.sys.entity.User;
import com.idenger.modules.sys.utils.UserUtils;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "${adminPath}/edu/comm/upload")
public class FileBackUploadController extends BaseController {
    @RequestMapping(value = "applyImgs")
    public String applyImgs(HttpServletRequest request, HttpServletResponse response, Model model) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        String saveUrl =request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        User user = UserUtils.getUser();
        Map baseResponseMsg = new HashMap();
        if (user == null) {
            baseResponseMsg.put("errno", "-1");
            return renderString(response, baseResponseMsg);
        }
        List uploadPaths = new ArrayList();
        String type = request.getParameter("type");
        String currentFolder = request.getParameter("currentFolder");// 当前文件夹可指定为模块名

        if ("DateTime".equals(currentFolder)) {
            Calendar date = Calendar.getInstance();
            currentFolder = File.separator + "article" + File.separator + date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1);
        }
        String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL
                + user.getId() + "/" + type + (currentFolder != null ? currentFolder : "");
        Boolean isUpload = FileUtils.createDirectory(FileUtils.path(realPath));

        //此处是直接采用Spring的上传
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileFullname = mf.getOriginalFilename();
            fileFullname = fileFullname.replace('&', 'a');
            fileFullname = fileFullname.replace(',', 'b');
            fileFullname = fileFullname.replace('，', 'c');
            // 文件类型限制
            String[] allowedType = { "image/bmp", "image/gif", "image/jpeg", "image/png" };
            boolean allowed = Arrays.asList(allowedType).contains(mf.getContentType());
            if (!allowed) {
                logger.info("error|不支持的类型");
                baseResponseMsg.put("errno", "-2");
                return renderString(response, baseResponseMsg);
            }

            // 图片大小限制
            if (mf.getSize() > 5 * 1024 * 1024) {
                logger.info("error|大小不能超过5M\"");
                baseResponseMsg.put("errno", "-2");
                return renderString(response, baseResponseMsg);
            }

            //检查扩展名
            String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

            File uploadFile = new File(realPath + newFileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                uploadPaths.add(saveUrl + Global.USERFILES_BASE_URL
                        + user.getId() + "/" + type + (currentFolder != null ? currentFolder : "") + newFileName);
                baseResponseMsg.put("errno", "0");
                baseResponseMsg.put("data", uploadPaths);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("上传文件失败");
                baseResponseMsg.put("errno", "-2");

            }
        }
        //上传结束
        return renderString(response, baseResponseMsg);
    }
    
}
